const checkAuth = () => {
    console.log('event.html: 开始认证检查');
    
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        console.log('用户未认证，重定向到登录页');
        AuthManager.redirectToLogin();
        return;
    }
    
    // 检查token有效性
    AuthManager.verifyToken()
        .then(() => {
            console.log('Token验证成功，检查页面访问权限...');
            
            // 在初始化页面前进行权限检查
            if (window.PermissionManager && !window.PermissionManager.hasPermission('EVENT_MANAGEMENT', 'access')) {
                // 如果没有权限，显示拒绝访问页面并停止后续操作
                PermissionManager.showAccessDenied('您没有权限访问事件管理页面');
                return;
            }

            console.log('权限检查通过，初始化页面');
            pageInit();
        })
        .catch(error => {
            console.error('Token验证失败:', error);
            AuthManager.redirectToLogin();
        });
};

// 页面初始化
function pageInit() {
    // 初始化权限管理器
    if (window.PermissionManager && window.AuthManager) {
        const userInfo = window.AuthManager.getUserInfo();
        if (userInfo) {
            window.PermissionManager.init(userInfo);
            window.PermissionManager.initEventPermissions();
        }
    }
    
    // 加载事件数据
    loadEvents();
    loadEventTypes();
    loadHandlers();
    loadStatistics();
}

// 加载事件列表
async function loadEvents(filters = {}) {
    try {
        const headers = AuthManager.getAuthHeaders();
        headers['Content-Type'] = 'application/json';

        // 构建查询参数
        const queryParams = new URLSearchParams();
        if (filters.status) queryParams.append('status', filters.status);
        if (filters.priority) queryParams.append('priority', filters.priority);
        if (filters.severity) queryParams.append('severity', filters.severity);
        if (filters.eventTypeId) queryParams.append('eventTypeId', filters.eventTypeId);
        if (filters.handlerId) queryParams.append('handlerId', filters.handlerId);

        const url = `/ercms/api/events${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
        const response = await fetch(url, {
            headers: headers
        });
        const result = await response.json();
        
        if (result.success) {
            displayEvents(result.data);
        } else {
            console.error('加载事件失败:', result.message);
        }
    } catch (error) {
        console.error('加载事件失败:', error);
    }
}

// 显示事件列表
function displayEvents(events) {
    const container = document.getElementById('eventsContainer');
    
    if (!events || events.length === 0) {
        container.innerHTML = '<div class="col-12 text-center"><p>暂无事件数据</p></div>';
        return;
    }

    let html = '';
    events.forEach(event => {
    const statusClass = getStatusClass(event.status);
    const priorityClass = getPriorityClass(event.priority);
    const severityClass = getSeverityClass(event.severity);
    
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card event-card">
            <div class="card-body">
                        <h5 class="card-title">${event.title || '未命名事件'}</h5>
                        <p class="card-text">${event.description || '无描述'}</p>
                <div class="mb-2">
                            <span class="badge ${statusClass} me-1">${getStatusText(event.status)}</span>
                    <span class="badge ${priorityClass} me-1">${getPriorityText(event.priority)}</span>
                    <span class="badge ${severityClass}">${getSeverityText(event.severity)}</span>
                </div>
                        <p class="card-text"><small class="text-muted">
                            <i class="bi bi-geo-alt"></i> ${event.location || '未知地点'}<br>
                            <i class="bi bi-clock"></i> ${formatDateTime(event.startTime)}
                        </small></p>
                        <div class="d-flex gap-2">
                            <a href="/ercms/dispatch/event/${event.id}" class="btn btn-primary btn-sm">查看详情</a>
                            ${(event.status === 'RESOLVED' || event.status === 'CLOSED' || event.status==='COMPLETED') ? 
                                `<button class="btn btn-info btn-sm" onclick="viewTaskReports(${event.id})">
                                    <i class="bi bi-file-text"></i> 查看报告
                                </button>` : ''
                            }
                            <button class="btn btn-danger btn-sm event-delete-btn" onclick="deleteEvent(${event.id}, '${event.title || '未命名事件'}')">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                    </div>
                    </div>
            </div>
        </div>
    `;
    });
    
    container.innerHTML = html;
}

// 获取状态样式类
function getStatusClass(status) {
    const classMap = {
        'PENDING': 'bg-warning',
        'ASSIGNED': 'bg-info',
        'IN_PROGRESS': 'bg-primary',
        'RESOLVED': 'bg-success',
        'CLOSED': 'bg-secondary'
    };
    return classMap[status] || 'bg-secondary';
}

// 获取优先级样式类
function getPriorityClass(priority) {
    const classMap = {
        'LOW': 'bg-success',
        'MEDIUM': 'bg-warning',
        'HIGH': 'bg-danger',
        'CRITICAL': 'bg-danger'
    };
    return classMap[priority] || 'bg-secondary';
}

// 获取严重程度样式类
function getSeverityClass(severity) {
    const classMap = {
        'MINOR': 'bg-success',
        'MODERATE': 'bg-warning',
        'SEVERE': 'bg-danger',
        'CRITICAL': 'bg-danger'
    };
    return classMap[severity] || 'bg-secondary';
}

// 获取状态文本
function getStatusText(status) {
    const textMap = {
        'PENDING': '待处理',
        'ASSIGNED': '已分配',
        'IN_PROGRESS': '处理中',
        'RESOLVED': '已解决',
        'CLOSED': '已关闭'
    };
    return textMap[status] || status;
}

// 获取优先级文本
function getPriorityText(priority) {
    const textMap = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'CRITICAL': '紧急'
    };
    return textMap[priority] || priority;
}

// 获取严重程度文本
function getSeverityText(severity) {
    const textMap = {
        'MINOR': '轻微',
        'MODERATE': '一般',
        'SEVERE': '严重',
        'CRITICAL': '特大'
    };
    return textMap[severity] || severity;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    
    try {
    const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (error) {
        return dateTimeStr;
    }
}

// 加载事件类型
async function loadEventTypes() {
    try {
        const headers = AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/events/event-types', {
            headers: headers
        });
        const result = await response.json();
        
        if (result.success) {
            // 更新筛选区的事件类型选择器
            const eventTypeFilter = document.getElementById('eventTypeFilter');
            let filterOptions = '<option value="">全部类型</option>';
            result.data.forEach(type => {
                filterOptions += `<option value="${type.id}">${type.name}</option>`;
            });
            eventTypeFilter.innerHTML = filterOptions;

            // 更新创建事件表单的事件类型选择器
            const createEventType = document.getElementById('createEventTypeId');
            if (createEventType) {  // 确保元素存在
                let createOptions = '<option value="">请选择事件类型</option>';
                result.data.forEach(type => {
                    createOptions += `<option value="${type.id}">${type.name}</option>`;
                });
                createEventType.innerHTML = createOptions;
            }
        } else {
            console.error('加载事件类型失败:', result.message);
        }
    } catch (error) {
        console.error('加载事件类型失败:', error);
    }
}

// 加载处理人
async function loadHandlers() {
    try {
        const headers = AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/users', {
            headers: headers
        });
        const result = await response.json();
        
        if (result.success) {
            const handlerFilter = document.getElementById('handlerFilter');
            
            let options = '<option value="">全部处理人</option>';
            result.data.forEach(user => {
                options += `<option value="${user.id}">${user.realName || user.username}</option>`;
            });
            
            handlerFilter.innerHTML = options;
        }
    } catch (error) {
        console.error('加载处理人失败:', error);
    }
}

// 加载统计数据
async function loadStatistics() {
    try {
        const headers = AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/events/statistics', {
            headers: headers
        });
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('totalEvents').textContent = result.data.totalEvents || 0;
            document.getElementById('pendingEvents').textContent = result.data.pendingEvents || 0;
            document.getElementById('inProgressEvents').textContent = result.data.inProgressEvents || 0;
            document.getElementById('resolvedEvents').textContent = result.data.resolvedEvents || 0;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 应用筛选
function applyFilters() {
    const filters = {
        status: document.getElementById('statusFilter').value,
        priority: document.getElementById('priorityFilter').value,
        severity: document.getElementById('severityFilter').value,
        eventTypeId: document.getElementById('eventTypeFilter').value,
        handlerId: document.getElementById('handlerFilter').value
    };

    // 移除空值
    Object.keys(filters).forEach(key => {
        if (!filters[key]) {
            delete filters[key];
        }
    });

    loadEvents(filters);
}

// 清除筛选
function clearFilters() {
    document.getElementById('statusFilter').value = '';
    document.getElementById('priorityFilter').value = '';
    document.getElementById('severityFilter').value = '';
    document.getElementById('eventTypeFilter').value = '';
    document.getElementById('handlerFilter').value = '';
    loadEvents();
}

// 创建事件相关功能
let createEventMap = null;
let createEventMarker = null;

// 初始化创建事件的地图
function initCreateEventMap() {
    if (!createEventMap) {
        createEventMap = new AMap.Map('eventMap', {
            zoom: 13,
            center: [116.397428, 39.90923]
        });

        // 加载地理编码插件
        AMap.plugin(['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch'], function(){
            const geocoder = new AMap.Geocoder({
                radius: 1000,
                extensions: "all"
            });
            
            const autoComplete = new AMap.AutoComplete({
                input: "location"
            });
            
            const placeSearch = new AMap.PlaceSearch({
                map: createEventMap
            });

            // 点击地图添加标记
            createEventMap.on('click', function(e) {
                const lngLat = e.lnglat;
                const coordinateString = `${lngLat.getLng()},${lngLat.getLat()}`;
                document.getElementById('lnglat').value = coordinateString;
                
                // 调试日志：验证坐标设置
                console.log('地图点击 - 设置坐标:');
                console.log('- 原始坐标对象:', lngLat);
                console.log('- 经度:', lngLat.getLng());
                console.log('- 纬度:', lngLat.getLat());
                console.log('- 坐标字符串:', coordinateString);
                console.log('- 隐藏字段值:', document.getElementById('lnglat').value);
                
                // 更新或添加标记
                if (createEventMarker) {
                    createEventMarker.setPosition(lngLat);
                } else {
                    createEventMarker = new AMap.Marker({
                        position: lngLat,
                        map: createEventMap
                    });
                }

                // 反向地理编码获取地址
                geocoder.getAddress(lngLat, function(status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        const address = result.regeocode;
                        let locationName = '';
                        
                        // 构建详细地址
                        if (address.formattedAddress) {
                            // 移除省市前缀，保留详细地址
                            let formattedAddress = address.formattedAddress;
                            const province = address.addressComponent.province;
                            const city = address.addressComponent.city;
                            if (formattedAddress.startsWith(province)) {
                                formattedAddress = formattedAddress.substring(province.length);
                            }
                            if (formattedAddress.startsWith(city)) {
                                formattedAddress = formattedAddress.substring(city.length);
                            }
                            locationName = formattedAddress.trim();
                        }
                        
                        // 如果有兴趣点信息，添加到地址中
                        if (address.pois && address.pois.length > 0) {
                            const nearestPoi = address.pois[0];
                            locationName = `${nearestPoi.name}附近 (${locationName})`;
                        }
                        
                        document.getElementById('location').value = locationName;
                    }
                });
            });

            // 地址输入框自动完成
            autoComplete.on('select', function(e){
                placeSearch.search(e.poi.name);
                if (e.poi.location) {
                    const lngLat = e.poi.location;
                    const coordinateString = `${lngLat.lng},${lngLat.lat}`;
                    document.getElementById('lnglat').value = coordinateString;
                    document.getElementById('location').value = e.poi.name;
                    
                    // 调试日志：验证坐标设置
                    console.log('地址选择 - 设置坐标:');
                    console.log('- POI名称:', e.poi.name);
                    console.log('- 原始坐标对象:', lngLat);
                    console.log('- 经度:', lngLat.lng);
                    console.log('- 纬度:', lngLat.lat);
                    console.log('- 坐标字符串:', coordinateString);
                    console.log('- 隐藏字段值:', document.getElementById('lnglat').value);
                    
                    if (createEventMarker) {
                        createEventMarker.setPosition(lngLat);
                    } else {
                        createEventMarker = new AMap.Marker({
                            position: lngLat,
                            map: createEventMap
                        });
                    }
                    // 将地图中心移动到选中的位置
                    createEventMap.setCenter(lngLat);
                }
            });
        });
    }
}

// 监听创建事件模态框的显示
document.getElementById('createEventModal').addEventListener('shown.bs.modal', function () {
    initCreateEventMap();
    // 确保事件类型已加载
    loadEventTypes();
});

// 提交创建事件
async function submitCreateEvent() {
    try {
        // 表单验证
        const title = document.getElementById('title').value.trim();
        const eventTypeId = document.getElementById('createEventTypeId').value;
        const description = document.getElementById('description').value.trim();
        const location = document.getElementById('location').value.trim();
        const lnglat = document.getElementById('lnglat').value;
        const priority = document.getElementById('priority').value;
        const severity = document.getElementById('severity').value;

        // 调试日志：检查坐标数据
        console.log('坐标数据检查:');
        console.log('- lnglat字段值:', lnglat);
        console.log('- lnglat字段类型:', typeof lnglat);
        console.log('- lnglat是否为空:', !lnglat || lnglat.trim() === '');

        // 验证必填字段
        if (!title) {
            alert('请输入事件标题');
            return;
        }
        if (!eventTypeId) {
            alert('请选择事件类型');
            return;
        }
        if (!location) {
            alert('请选择或输入事发地点');
        return;
    }

        const formData = {
            title: title,
            eventTypeId: parseInt(eventTypeId), // 确保是数字
            description: description || '',
            location: location,
            lnglat: lnglat || '',
            priority: priority || 'MEDIUM',
            severity: severity || 'MODERATE'
        };

        console.log('准备提交的数据:', formData);
        console.log('坐标数据在formData中:', formData.lnglat);

        const headers = AuthManager.getAuthHeaders();
        headers['Content-Type'] = 'application/json';

        const response = await fetch('/ercms/dispatch/api/events', {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(formData)
        });

        console.log('服务器响应状态:', response.status);
        const result = await response.json();
        console.log('服务器响应数据:', result);
        
        if (response.ok && result.success) {
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('createEventModal'));
            modal.hide();
            
            // 重置表单
            document.getElementById('createEventForm').reset();
            if (createEventMarker) {
                createEventMarker.setMap(null);
                createEventMarker = null;
            }
            document.getElementById('lnglat').value = '';
            
            // 刷新事件列表
            loadEvents();
            
            // 显示成功消息
            alert('事件创建成功！');
        } else {
            const errorMessage = result.message || '创建失败，请检查输入数据';
            console.error('创建事件失败:', errorMessage);
            alert('创建失败: ' + errorMessage);
        }
    } catch (error) {
        console.error('创建事件时发生错误:', error);
        alert('创建事件失败: ' + (error.message || '请检查网络连接'));
    }
}

// 查看任务报告
async function viewTaskReports(eventId) {
    try {
        console.log('查看事件任务报告:', eventId);
        
        // 显示加载状态
        const contentDiv = document.getElementById('taskReportsContent');
        contentDiv.innerHTML = '<div class="text-center"><i class="bi bi-hourglass-split"></i> 正在加载报告...</div>';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('taskReportsModal'));
        modal.show();
        
        // 获取任务报告数据
        const headers = AuthManager.getAuthHeaders();
        const response = await fetch(`/ercms/api/completion/event/${eventId}/reports`, {
            headers: headers
        });
        
        const result = await response.json();
        console.log('任务报告响应:', result);
        
        if (result.success) {
            displayTaskReports(result.data, eventId);
        } else {
            contentDiv.innerHTML = `
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i>
                    暂无任务报告数据
                </div>
            `;
        }
    } catch (error) {
        console.error('加载任务报告失败:', error);
        const contentDiv = document.getElementById('taskReportsContent');
        contentDiv.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-x-circle"></i>
                加载任务报告失败: ${error.message}
            </div>
        `;
    }
}

// 显示任务报告
function displayTaskReports(reports, eventId) {
    const contentDiv = document.getElementById('taskReportsContent');
    
    if (!reports || reports.length === 0) {
        contentDiv.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i>
                该事件暂无任务报告
            </div>
        `;
        return;
    }
    
    let html = `
        <div class="mb-3">
            <h6>事件ID: ${eventId}</h6>
            <p class="text-muted">共 ${reports.length} 份报告</p>
        </div>
    `;
    
    reports.forEach((report, index) => {
        html += `
            <div class="card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">报告 #${index + 1}</h6>
                    <small class="text-muted">${formatDateTime(report.reportTime)}</small>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <strong>报告内容:</strong>
                        <p class="mt-2">${report.content || '无内容'}</p>
                    </div>
                    ${report.reporterName ? `
                        <div class="mb-2">
                            <strong>报告人:</strong> ${report.reporterName}
                        </div>
                    ` : ''}
                    ${report.photos && report.photos.length > 0 ? `
                        <div class="mb-3">
                            <strong>现场照片:</strong>
                            <div class="row mt-2">
                                ${report.photos.map(photo => `
                                    <div class="col-md-4 mb-2">
                                        <img src="/ercms/api/completion/photos/${photo.id}/file" 
                                             class="img-fluid rounded" 
                                             alt="现场照片"
                                             style="max-height: 200px; object-fit: cover;"
                                             onclick="viewPhoto('/ercms/api/completion/photos/${photo.id}/file')">
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    contentDiv.innerHTML = html;
}

// 查看照片
function viewPhoto(photoUrl) {
    // 创建照片查看模态框
    const photoModal = document.createElement('div');
    photoModal.className = 'modal fade';
    photoModal.id = 'photoModal';
    photoModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">现场照片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="${photoUrl}" class="img-fluid" alt="现场照片">
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面并显示
    document.body.appendChild(photoModal);
    const modal = new bootstrap.Modal(photoModal);
    modal.show();
    
    // 模态框关闭后移除元素
    photoModal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(photoModal);
    });
}

// 删除事件
async function deleteEvent(eventId, eventTitle) {
    // 权限检查
    if (!window.PermissionManager || !window.PermissionManager.hasPermission('EVENT_MANAGEMENT', 'delete')) {
        alert('您没有权限删除事件');
        return;
    }
    
    // 显示删除确认模态框
    document.getElementById('deleteEventTitle').textContent = eventTitle;
    
    // 设置确认删除按钮的事件处理
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    confirmDeleteBtn.onclick = async () => {
        await performDeleteEvent(eventId, eventTitle);
    };
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('deleteEventModal'));
    modal.show();
}

// 执行删除事件操作
async function performDeleteEvent(eventId, eventTitle) {
    try {
        const headers = AuthManager.getAuthHeaders();
        headers['Content-Type'] = 'application/json';
        
        const response = await fetch(`/ercms/api/events/${eventId}`, {
            method: 'DELETE',
            headers: headers
        });
        
        const result = await response.json();
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteEventModal'));
        modal.hide();
        
        if (response.ok && result.success) {
            // 删除成功
            showSuccessMessage('事件删除成功！');
            // 刷新事件列表
            loadEvents();
            // 刷新统计数据
            loadStatistics();
        } else {
            const errorMessage = result.message || result.error || '删除失败';
            showErrorMessage('删除失败: ' + errorMessage);
        }
    } catch (error) {
        console.error('删除事件失败:', error);
        showErrorMessage('删除事件失败: ' + (error.message || '网络错误'));
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteEventModal'));
        modal.hide();
    }
}

// 显示成功消息
function showSuccessMessage(message) {
    // 创建成功提示
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-check-circle"></i> ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 显示错误消息
function showErrorMessage(message) {
    // 创建错误提示
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-x-circle"></i> ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 5秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 5000);
}

// 页面加载完成后进行认证检查
document.addEventListener('DOMContentLoaded', checkAuth);
